package com.ziqi.hututubackend.controller;

import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.ziqi.hututubackend.annotation.AuthCheck;
import com.ziqi.hututubackend.common.BaseResponse;
import com.ziqi.hututubackend.common.ResultUtils;
import com.ziqi.hututubackend.constant.UserConstant;
import com.ziqi.hututubackend.exception.BusinessException;
import com.ziqi.hututubackend.exception.ErrorCode;
import com.ziqi.hututubackend.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private CosManager cosManager;

    /**
     * 测试文件上传功能
     * @param multipartFile
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String filepath = String.format("/test/%s", filename);  //取出路径

        File file = null; //开始设置为空，以便后面删除本地文件
        try {
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            // 调用编写的上传文件函数
            cosManager.putObject(filepath, file);
            // 返回可访问地址
            return ResultUtils.success(filepath);
        } catch (IOException e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
//            文件上传完成后删除本地（服务器）文件，以免占用额外空间
            if(file != null) {
                //删除临时文件
                boolean delete = file.delete();
//                判断是否删除成功
                if(!delete) {
                    log.error("文件删除错误, filepath = {}", filepath);
                }
            }
        }
    }

    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/download")
    public void testDownloadFile(String filepath, HttpServletResponse response) throws IOException {
        //创建流对象，用于保存文件对象
        COSObjectInputStream cosObjectInput = null;
        try {
            // 获取文件对象
            COSObject cosObject = cosManager.getObject(filepath);
            cosObjectInput = cosObject.getObjectContent();
            // 将流对象处理
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应类型和响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception error) {
            log.error("文件下载失败, filepath = " + filepath, error);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            if(cosObjectInput != null) {
                cosObjectInput.close();
            }
        }


    }
}
